<%@ page language="java" import="org.apache.commons.lang.StringUtils" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ page import="java.io.File" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.OutputStream" %>
<%@ page import="java.io.RandomAccessFile" %>
<%@ page import="up7.utils.PathTool" %>
<%
	out.clear();
	/*
		下载文件块，针对于合并后的文件处理
		相关错误：
			getOutputStream() has already been called for this response
				解决方法参考：http://stackoverflow.com/questions/1776142/getoutputstream-has-already-been-called-for-this-response
		更新记录：
			2015-05-13 创建
			2017-05-06 增加业务逻辑数据，简化处理逻辑
			2017-05-14 优化逻辑
			2017-08-15 精简参数，优化代码，取消文件夹逻辑判断，取消redis访问操作
	*/
	String pathSvr 		= request.getHeader("pathSvr");
	String blockIndex 	= request.getHeader("blockIndex");//基于1
	String fileOffset	= request.getHeader("fileOffset");
	String blockSize	= request.getHeader("blockSize");//逻辑块大小
	pathSvr	 			= PathTool.url_decode(pathSvr);

	if (
			StringUtils.isEmpty(pathSvr)||
					StringUtils.isEmpty(blockIndex)
		)
	{
		System.out.println("pathSvr:".concat(pathSvr));
		System.out.println("blockIndex:".concat(blockIndex));
		System.out.println("blockSize:".concat(blockSize));
		System.out.println("f_down.jsp 业务逻辑参数为空。");
		return;
	}

	//文件不存在
	File f = new File(pathSvr);
	if(!f.exists())
	{
		response.setStatus(500);
		OutputStream os = response.getOutputStream();
		System.out.println(String.format("%s 文件不存在",pathSvr));
		os.close();
		return;
	}

	RandomAccessFile raf = new RandomAccessFile(pathSvr,"r");
	FileInputStream in = new FileInputStream( raf.getFD() );

	long dataToRead = Long.parseLong(blockSize);
	response.setContentType("application/x-download");
	response.setHeader("Pragma","No-cache");
	response.setHeader("Cache-Control","no-cache");
	response.setDateHeader("Expires", 0);
	response.addHeader("Content-Length",Long.toString(dataToRead) );

	OutputStream os = null;
	try
	{
		os = response.getOutputStream();
		long offset_begin = Long.parseLong(fileOffset);
		in.skip(offset_begin);//定位索引

		byte[] buffer = new byte[1048576];//1MB
		int len = 0;
		out.clear();//

		while( dataToRead > 0 )
		{
			len = in.read(buffer,0,Math.min(1048576,(int)dataToRead));
			os.write(buffer, 0, len);
			os.flush();
			response.flushBuffer();
			buffer = new byte[1048576];
			dataToRead = dataToRead - len;
		}
		os.close();
		os = null;

		out.clear();
		out = pageContext.pushBody();
	}
	catch(Exception e){response.setStatus(500);}
	finally
	{
		if(os != null)
		{
			os.close();
			os = null;
		}
		out.clear();
		out = pageContext.pushBody();
	}
	in.close();
	in = null;
%>